/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package android.reasons;

import static android.app.Activity.RESULT_OK;
import android.app.ContextoAndroid;
import android.app.FontManager;
import android.app.Mensaje;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.entidades.Usuario;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import static android.reasons.Inicio.RESULT_LOAD_IMAGE;
import android.view.View;
import android.view.View.OnClickListener;
import android.web.service.WebService;
import android.widget.LinearLayout;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import java.io.File;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;

/**
 *
 * @author efraingutierrez
 */
public class SignIn implements OnClickListener 
{
    private Inicio inicio;
    private Button btnChoose;
    private ImageButton accept,atras;
    private ImageView imgDisplay;
    private LinearLayout abs;
    private EditText etID,etPassword,etNombre;
    private String UploadImagePath,UploadImageName;
    private ProgressDialog dialog;
    private Boolean imgFlag = false;
    
    public SignIn(Inicio inicio)
    {
        this.inicio = inicio;
        inicio.setContentView(R.layout.signin);
        abs = (LinearLayout)inicio.findViewById(R.id.abssignin);
        abs.setBackgroundResource(R.drawable.turquesa);
        accept = (ImageButton)inicio.findViewById(R.id.btnOkSignIn);
        atras = (ImageButton)inicio.findViewById(R.id.btnAtrasS);
        imgDisplay = (ImageView)inicio.findViewById(R.id.imgView);
        btnChoose = (Button)inicio.findViewById(R.id.btnFoto);
        btnChoose.setOnClickListener(this);
        etID = (EditText)inicio.findViewById(R.id.etIDSignIn);
        etPassword = (EditText)inicio.findViewById(R.id.etPassSignIn);
        etNombre = (EditText)inicio.findViewById(R.id.etNombreSignIn);
        accept.setOnClickListener(this);
        atras.setOnClickListener(this);
        FontManager.changeFont(abs);
    }
    
    public void onClick(View arg0) 
    {
        
        if(arg0.getId() == R.id.btnFoto)
        {
            Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            inicio.startActivityForResult(i, Inicio.RESULT_LOAD_IMAGE);
        }
        else if(arg0.getId() == R.id.btnOkSignIn)
        {
            final String nickStr = etID.getText().toString();
            final String passStr = etPassword.getText().toString();
            final String nombre = etNombre.getText().toString();

            if(!nickStr.equals("") && !passStr.toString().equals("") && !nombre.equals(""))
            {
                if(imgFlag)
                {
                     if(WebService.conexionInternert())
                     {
                         new WebPetition().execute(UploadImagePath,UploadImageName,nickStr,passStr,nombre);
                     }
                     else Mensaje.Mostrar("Error: No Existe Conexion a Internet");
                }
                else Mensaje.Mostrar("Error: No Ha Seleccionado Una Imagen Vàlida");
               
            }
            else Mensaje.Mostrar("Error: Datos Incompletos");
        }
        else
        {
            regresar();
        }
    }

    void regresar()
    {
        inicio.back();
    }
    
    void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) 
        {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = inicio.getContentResolver().query(selectedImage,filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            UploadImagePath = cursor.getString(columnIndex);
            cursor.close();
            File imgFile = new  File(UploadImagePath);
            Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
            imgDisplay.setImageBitmap(myBitmap);
            UploadImageName = imgFile.getName();
            imgFlag = true;
            // String picturePath contains the path of selected Image
        }
    }
    
    public void save(String name)
    {
          
    }
    private class WebPetition extends AsyncTask<String, Integer, Boolean> {
        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(ContextoAndroid.context);
            dialog.setIndeterminate(false);
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.setCancelable(true);
            dialog.setMessage("Registrador Usuario...");
            dialog.show();
        }
        @Override
        protected Boolean doInBackground(String... params) 
        {
            Boolean b = android.web.service.Photo.uploadPhoto(params[0]);
            ArrayList<NameValuePair> lst = new ArrayList<NameValuePair>();
            lst.add(new BasicNameValuePair("id",params[2]));
            lst.add(new BasicNameValuePair("password",params[3]));
            lst.add(new BasicNameValuePair("foto",params[1]));
            lst.add(new BasicNameValuePair("nombre",params[4]));
            lst.add(new BasicNameValuePair("tipo","0"));
            JSONArray array = WebService.getJSONArray(lst, "Alta", "Controladores/nuevoUsuario.php");
            try {
                String str = array.getString(0);
                if(!str.equals("1"))
                    return false;
            } catch (Exception ex) {
                return false;
            }
            if(b)
            {
                String correo = params[2];
                String pass = params[3];
                String nombre = params[4];
                String foto = params[1];
                int tipo = 0;
                Usuario u = new Usuario(correo,pass,nombre,foto,tipo);
                ContextoAndroid.usuario = u;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) 
        {
            dialog.dismiss();
            if(result)
            {
                regresar();
            }
        }
        @Override
        protected void onProgressUpdate(Integer... values) 
        {
            dialog.setMessage("Cargando...");
            dialog.setProgress(values[0]);
        }
    }
}
